<?php

namespace app\api\controller\examination;
require_once EXTEND_PATH . 'qrcode/vendor/autoload.php';
use app\common\controller\Api;
use app\api\model\v1\UserCheck;
use app\common\library\Sms as Smslib;
use think\Config;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\Writer\PngWriter;
use think\Db;
use think\Request;
use app\common\model\User as UserModel;



/**
 * 报名考试
 */
class Index extends Api
{
    protected $noNeedLogin = ['signup','recommend','jigoumajor','jigoujibie','index','examolan','major','getMechanismCategory','examolando','getmechanismplanTime','putworld','checkUser'];
    protected $noNeedRight = ['*'];


    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
        $this->message=model('admin/examination/Message');
        $this->plan=model('admin/examination/Plan');
        $this->user_check=model('admin/user/Check');
//        $this->mechanismplan=model('admin/examination/Mechanismplan');
        $this->mechanism_category=model('admin/mechanism/Category');
        $this->mechanismplan=model('admin/examination/Mechanismplan');
        $this->student=model('admin/user/Student');
        $this->usersignup=model('admin/mechanism/Usersignup');
        $this->courses_category=model('admin/courses/Category');
        $this->user=model('admin/User');
        $this->student=model('admin/user/Student');



        //mechanism_category

    }

    /**
     * 考试管理
     */

    public function index($page=1,$limit=10,$courses_category_id=null,$mechanism_category_topid=null,$mechanism_category_id=null,$check_id=null,$keywords=null){

         $where=[];

        if($courses_category_id!=null){
            $where['m.courses_category_id']=['=',$courses_category_id];
        }
        if($mechanism_category_topid!=null){
            $where['m.mechanism_category_topid']=['=',$mechanism_category_topid];
        }
        if($mechanism_category_id!=null){
            $where['mechanism_category_id']=['=',$mechanism_category_id];
        }

         if($check_id!=null){
            // $where['m.admin_id']=['=',$check_id];
            $examination_message_id= $this->mechanismplan->where('admin_id',$check_id)->column('examination_message_id');
             $where['id']=['in',$examination_message_id];

         }



         if($keywords!=null){

         }


      $list=  $this->message
              ->alias('m')
//             ->join('__USER_CHECK__ u','m.admin_id = u.id')
//              ->where()
          ->where($where)
          ->paginate($limit);
          foreach ($list as $key=>$value){
                  $planList=$this->plan->where('end_time','>',time())->where('examination_message_id',$value['id'])->select();
              foreach ($planList as $k=>$v){
                  $planList[$k]['time_text']=date('y年m月d日',$v['time']);
                  $planList[$k]['end_time_text']=date('y年m月d日',$v['end_time']);
              }
              $list[$key]['plan']=$planList;
          }
         $this->success('ok',$list);


    }

    /**
     * 考试/分类/机构/专业/级别考试计划
     */
    public function examolan($user_check_id=null,$examination_message_id=null,$examination_plan_id=null,$courses_category_id=null,$mechanism_category_topid=null,
                             $mechanism_category_id=null){
        if($user_check_id!=null){
        $where['m.admin_id']=['=',$user_check_id];
        }
        if($examination_message_id!=null){
            $where['m.examination_message_id']=['=',$examination_message_id];
        }
        if($examination_message_id!=null){
            $where['m.examination_plan_id']=['=',$examination_plan_id];
        }
        if($examination_message_id!=null){
            $where['m.courses_category_id']=['=',$courses_category_id];
        }
        if($examination_message_id!=null){
            $where['m.mechanism_category_topid']=['=',$mechanism_category_topid];
        }
        if($examination_message_id!=null){
            $where['m.mechanism_category_id']=['=',$mechanism_category_id];
        }
        $where['end_time']=['>',time()];

      $mechanismplan=  $this->mechanismplan
          ->alias('m')
          ->join('__USER_CHECK__ u','m.admin_id= u.id')
          ->field('m.*,u.name')
          ->where($where)->select();



      $this->success('OK',$mechanismplan);

    }

    /**
     * 获得报名机构及级别
     * @param int $pid
     */
    public function getMechanismCategory($pid=0){

        $where=[];
        if($pid==0){
            $mechanismplan_ids=  $this->mechanismplan
                ->where('end_time','<',time())
                ->group('mechanism_category_topid')
                ->column('mechanism_category_topid');
        }else{
            $mechanismplan_ids=  $this->mechanismplan
                ->where('end_time','<',time())
                ->group('mechanism_category_id')
                ->column('mechanism_category_id');
        }

        if($pid!=0){
            $where['pid']=['=',$pid];
        }

        $where['id']=['in',$mechanismplan_ids];

      $mechanism_category=  $this->mechanism_category->where($where)->select();
      $this->success('OK',$mechanism_category);

    }

    /**
     * 获得机构名称
     * @param null $user_check_id
     * @param null $examination_message_id
     * @param null $examination_plan_id
     * @param null $courses_category_id
     * @param null $mechanism_category_topid
     * @param null $mechanism_category_id
     */
    public function examolando($end_time,$mechanism_category_id){

        $where['end_time']=['>',strtotime($end_time)];
        $where['mechanism_category_id']=['=',$mechanism_category_id];
        $mechanismplan=  $this->mechanismplan
            ->alias('m')
            ->join('__USER_CHECK__ u','m.admin_id= u.id')
            ->field('m.*,u.name')
            ->where($where)->select();
        $this->success('OK',$mechanismplan);

    }

    /**
     * 时间
     * @param int $pid
     */
    public function getmechanismplanTime($mechanism_category_id){

        $where=[];

            $mechanismplan_ids=  $this->mechanismplan
                ->where('end_time','<',time())
                ->where('mechanism_category_id','=',$mechanism_category_id)
                ->group('end_time')
                ->select();
        $this->success('OK',$mechanismplan_ids);
    }

    /***
     * 手机号/身份证验证学员是否已入驻
     * @param $mobile
     */
        public  function checkUser($mobile=null,$id_card=null,$zuzhi=null){
            $where=[];
            if($mobile){
                $where['mobile']=['=',$mobile];
            }
            if($id_card){
                $where['id_card']=['=',$id_card];
            }
            if($zuzhi){
                $where['zuzhi']=['=',$zuzhi];
            }
         if($userinfo=$this->user->where($where)->find()){
             $str_arr=[];
             $juese_ids=explode(",",$userinfo['juese_ids']);
             if(in_array(1,$juese_ids)){
                 $str_arr[]="学员,";
             }
             if(in_array(2,$juese_ids)){
                 $str_arr[]="名师";
             }
             if(in_array(3,$juese_ids)){
                 $str_arr[]="实训基地";
             }
             if(in_array(4,$juese_ids)){
                 $str_arr[]="评价中心";
             }
             if(in_array(5,$juese_ids)){
                 $str_arr[]="学习中心";
             }
             if(in_array(6,$juese_ids)){
                 $str_arr[]="考核机构";
             }
             if(in_array(7,$juese_ids)){
                 $str_arr[]="企业";
             }
           $str=implode(",",$str_arr);
//             dump($str);
//             exit;
             if($mobile!=null){


                 $msg='您的手机号已注册'.$str.'请登录手机号进行操作';
             }
             if($id_card){
                 $msg='您的身份证号已注册'.$str.'，请登录身份证进行操作';
             }
             if($zuzhi){
                 $msg='您的组织机构代码已注册'.$str.'，请登录组织机构进行操作';
             }
             $this->success("OK",['code'=>0,'msg'=>$msg]);

         }else{
             //$this->success("OK",0);
             $this->success("OK",['code'=>1]);
         }

        }



    /**
     * 身份证验证学员入驻
     */
        public function signup($name,$mobile,$id_card,$captcha,$examination_mechanismplan_id,$usered_score=0,$invitation_code=null){
            $event = 'signup';
            if($mobile==null || $captcha==null){
                $this->error(__('手机号/短信验证码参数不全'));
            }

            if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('手机号不正确'));
            }


            try{
                db()->startTrans();
                if($this->auth->id==NULL){
                    $where1['mobile']=['=',$mobile];

                    if($this->user->where($where1)->where( " FIND_IN_SET(1,juese_ids)")->find()){
                        $this->error('手机号已注册过学员，请登陆账号号在提交');
                    }

                    $where2['id_card']=['=',$id_card];
                    if($this->user->where($where2)->where( " FIND_IN_SET(1,juese_ids)")->find()){
                        $this->error('身份证号已注册过学员，请登陆账号在提交');
                    }
                    if ($id_card) {
                        if (!isCreditNo($id_card)) {
                            $this->error('身份证号不正确');
                        }
                    }

                    //检测账户中是否有改手机号
                    if($userInfo=$this->user->where($where1)->find()){  //有这个手机号
                        $jiese_ids_arr= explode(",",$userInfo->juese_ids);
                        if(!in_array(1,$jiese_ids_arr)){ //没有学员身份的话加入学员身份
                            $jiese_ids_arr[]=1;
                            $this->user->where('id',$userInfo->id)->update(['jiese_ids'=>implode(",",$jiese_ids_arr)]);
                        }
                        $this->student::create(['user_id'=>$userInfo->id,'name'=>$name,'id_card'=>$id_card,'is_auth'=>'是']);

                    }else{ //没有这个手机号
                        //  $extend['id_card']=$id_card;


                        if($invitation_code!=''){

                            if($teacherInfo=Db::name('user_teacher')->where('invitation_code',$invitation_code)->find()){
                                $extend['teacher_id']=$teacherInfo['id'];
                            }else{
                                $this->error('邀请老师不存在');
                            }
                            $extend['invitation_code']=$invitation_code;
                        }

                        $extend['juese_ids']=1;

                        $ret = $this->auth->setRegister($name,$mobile, 'Aa123456', $id_card, $extend);
                           if($ret['code']==0){
                               $this->error($ret['msg']);
                           }
                      $r=$this->student::create(['user_id'=>$this->auth->id,'name'=>$name,'id_card'=>$id_card,'is_auth'=>'是']);
                    }



                }else{

                    if(!in_array(1,explode(",",$this->auth->juese_ids))){
                        $this->error('您还未入驻学员请先入驻');
                    }


                }

                $where['id']=['=',$examination_mechanismplan_id];
                if ($mechanismplanInfo = $this->mechanismplan->get($where)) {

                    if ($mechanismplanInfo->end_time < time()) {
                        $this->error('报名计划已过期');
                    }

                    if($this->usersignup->where('user_id',$this->auth->id)->where('paystate',1)->where('examination_mechanismplan_id',$examination_mechanismplan_id)->find()){
                        $this->error('您已报过名，无需重复报名');
                    }

                    //检测是否已报过名

                    if (!$user_checkInfo = $this->user_check->get($mechanismplanInfo['admin_id'])) {
                        $this->error('机构已不存在');
                    }
                    //获得报名用户基本信息
                    if (!$student = $this->student->where('user_id', $this->auth->id)->find()) {
                        $this->error('未入驻学员什么不能报名');
                    }

                    if ($student->is_auth != '是') {
                        $this->error('您还没有认证学员信息，请先认证');
                    }

                    if ($courses_categoryinfo = $this->courses_category->get($mechanismplanInfo['courses_category_id'])) {
                        $courses_category_name = $courses_categoryinfo['name'];
                    } else {
                        $courses_category_name = '';
                        $this->error('考试分类已删除或者不存在，请联系客服');
                    }
                    if ($examination_messageinfo = $this->message->get($mechanismplanInfo['examination_message_id'])) {
                        $examination_message_name = $examination_messageinfo['name'];
                    } else {
                        $this->error('考试已被删除，请联系客服');
                    }

                    if ($mechanism_category_zhuanye = $this->mechanism_category->get($mechanismplanInfo->mechanism_category_topid)) {
                        $mechanism_category_zhuanye = $mechanism_category_zhuanye['name'];
                    } else {
                        $this->error('专业已删除或者不存杂，请联系客服');
                    }

                    if ($mechanism_category_jibie = $this->mechanism_category->get($mechanismplanInfo->mechanism_category_id)) {
                        $mechanism_category_jibie = $mechanism_category_jibie['name'];
                    } else {
                        $this->error('专业已删除或者不存杂，请联系客服');
                    }


                    $order_sn = "SN" . date('Ymd', time()) . rand(10000, 99999);
                    $step = '已支付';
                    $paystate = 1;
                    $paytime = time();

                    if($usered_score!=0){
                        $mechanismplanInfo['price']=$mechanismplanInfo['price']-$usered_score/Config('site.score_bi');

                    }

                    if ($mechanismplanInfo['price'] > 0) {
                        $step = '待支付';
                        $paystate = 0;
                        $paytime = '';
                    }else{
                        UserModel::score(-$usered_score, $this->auth->id, '支付订单扣除订单号'.$order_sn);
                    }

                   // $data = ['userinfo' => $this->auth->getToken()];
                    $data = [

                        'order_sn' => $order_sn,
                        'name' => $student['name'],
                        'id_card' => $student['id_card'],
                        'card_front_image' => $student['card_front_image'],
                        'card_back_image' => $student['card_back_image'],
                        'sex' => $student['sex'],
                        'pinyin' => $student['pinyin'],
                        'oldname' => $student['oldname'],
                        'birthday' => $student['birthday'],
                        'minzu' => $student['minzu'],
                        'jiguan' => $student['jiguan'],
                        'last_image' => $student['last_image'],
                        'mianmao' => $student['mianmao'],
                        'xueli' => $student['xueli'],
                        'major' => $student['major'],
                        'school' => $student['school'],
                        'youbian' => $student['youbian'],
                        'biye_school' => $student['biye_school'],
                        'comeinschool' => $student['comeinschool'],
                        'address' => $student['address'],
                        'mobile' => $student['contact_mobile'],
                        'school_url' => $student['school_url'],
                        'chuanzhen' => $student['chuanzhen'],
                        'email' => $student['email'],
                        'user_check_id' => $mechanismplanInfo['admin_id'],
                        'courses_category_id' => $mechanismplanInfo['courses_category_id'],
                        'mechanism_category_topid' => $mechanismplanInfo['mechanism_category_topid'],
                        'mechanism_category_id' => $mechanismplanInfo['mechanism_category_id'],
                        'examination_message_id' => $mechanismplanInfo['examination_message_id'],
                        'examination_mechanismplan_id' => $examination_mechanismplan_id,
                        'time' => $mechanismplanInfo['time'],
                        'end_time' => $mechanismplanInfo['end_time'],
                        'price' => $mechanismplanInfo['price'],
                        'step' => $step,
                        'paystate' => $paystate,
                        'paytime' => $paytime,
                        'user_id' => $this->auth->id,
                        'user_check_name' => $user_checkInfo['name'],
                        'courses_category_name' => $courses_category_name,
                        'examination_message_name' => $examination_message_name,
                        'mechanism_category_zhuanye' => $mechanism_category_zhuanye,
                        'mechanism_category_jibie' => $mechanism_category_jibie,
                        'usered_score'=>$usered_score
                    ];

                    $r = $this->usersignup::Create($data);
                } else {
                    $this->error('报名计划不存在');
                }
                   $res=['orderIfo'=>$r,'token'=>$this->auth->getToken(),'juese_ids'=>1];
                db()->commit();
                $this->success('订单创建时间', $res);
            }catch (Exception $e){
                $this->error($e->getMessage());
                db()->rollback();

            }

        }



    /**
     * 报名考试
     * @param $mobile
     * @param $code
     * @param $user_check_id
     * @param $mechanism_category_topid
     * @param $mechanism_category_id
     * @param $examination_mechanismplan_id
     */
    public function signupold($mobile=null,$captcha=null,$examination_mechanismplan_id,$usered_score=0){
        $where['id']=['=',$examination_mechanismplan_id];
        $event = 'signup';
       if($mobile==null || $captcha==null){
           $this->error(__('手机号/短信验证码参数不全'));
       }

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }


            $ret = Smslib::setCheck($mobile, $captcha, $event);
            if (!$ret) {
                $this->error(__('短信验证码不正确'));
            }

            if ($mechanismplanInfo = $this->mechanismplan->get($where)) {

                if ($mechanismplanInfo->end_time < time()) {
                    $this->error('报名计划已过期');
                }

               if($this->usersignup->where('user_id',$this->auth->id)->where('paystate',1)->where('examination_mechanismplan_id',$examination_mechanismplan_id)->find()){
                   $this->error('您已报过名，无需重复报名');
               }

                //检测是否已报过名

                if (!$user_checkInfo = $this->user_check->get($mechanismplanInfo['admin_id'])) {
                    $this->error('机构已不存在');
                }
                //获得报名用户基本信息
                if (!$student = $this->student->where('user_id', $this->auth->id)->find()) {
                    $this->error('未入驻学员什么不能报名');
                }
                if ($student->is_auth != '是') {
                    $this->error('您还没有认证学员信息，请先认证');
                }

                if ($courses_categoryinfo = $this->courses_category->get($mechanismplanInfo['courses_category_id'])) {
                    $courses_category_name = $courses_categoryinfo['name'];
                } else {
                    $courses_category_name = '';
                    $this->error('考试分类已删除或者不存在，请联系客服');
                }
                if ($examination_messageinfo = $this->message->get($mechanismplanInfo['examination_message_id'])) {
                    $examination_message_name = $examination_messageinfo['name'];
                } else {
                    $this->error('考试已被删除，请联系客服');
                }

                if ($mechanism_category_zhuanye = $this->mechanism_category->get($mechanismplanInfo->mechanism_category_topid)) {
                    $mechanism_category_zhuanye = $mechanism_category_zhuanye['name'];
                } else {
                    $this->error('专业已删除或者不存杂，请联系客服');
                }

                if ($mechanism_category_jibie = $this->mechanism_category->get($mechanismplanInfo->mechanism_category_id)) {
                    $mechanism_category_jibie = $mechanism_category_jibie['name'];
                } else {
                    $this->error('专业已删除或者不存杂，请联系客服');
                }


                $order_sn = "SN" . date('Ymd', time()) . rand(10000, 99999);
                $step = '已支付';
                $paystate = 1;
                $paytime = time();

                if($usered_score!=0){
                    $mechanismplanInfo['price']=$mechanismplanInfo['price']-$usered_score/Config('site.score_bi');

                }

                if ($mechanismplanInfo['price'] > 0) {
                    $step = '待支付';
                    $paystate = 0;
                    $paytime = '';
                }else{
                    UserModel::score(-$usered_score, $this->auth->id, '支付订单扣除订单号'.$order_sn);
                }

                $data = [
                    'order_sn' => $order_sn,
                    'name' => $student['name'],
                    'id_card' => $student['id_card'],
                    'card_front_image' => $student['card_front_image'],
                    'card_back_image' => $student['card_back_image'],
                    'sex' => $student['sex'],
                    'pinyin' => $student['pinyin'],
                    'oldname' => $student['oldname'],
                    'birthday' => $student['birthday'],
                    'minzu' => $student['minzu'],
                    'jiguan' => $student['jiguan'],
                    'last_image' => $student['last_image'],
                    'mianmao' => $student['mianmao'],
                    'xueli' => $student['xueli'],
                    'major' => $student['major'],
                    'school' => $student['school'],
                    'youbian' => $student['youbian'],
                    'biye_school' => $student['biye_school'],
                    'comeinschool' => $student['comeinschool'],
                    'address' => $student['address'],
                    'mobile' => $student['contact_mobile'],
                    'school_url' => $student['school_url'],
                    'chuanzhen' => $student['chuanzhen'],
                    'email' => $student['email'],
                    'user_check_id' => $mechanismplanInfo['admin_id'],
                    'courses_category_id' => $mechanismplanInfo['courses_category_id'],
                    'mechanism_category_topid' => $mechanismplanInfo['mechanism_category_topid'],
                    'mechanism_category_id' => $mechanismplanInfo['mechanism_category_id'],
                    'examination_message_id' => $mechanismplanInfo['examination_message_id'],
                    'examination_mechanismplan_id' => $examination_mechanismplan_id,
                    'time' => $mechanismplanInfo['time'],
                    'end_time' => $mechanismplanInfo['end_time'],
                    'price' => $mechanismplanInfo['price'],
                    'step' => $step,
                    'paystate' => $paystate,
                    'paytime' => $paytime,
                    'user_id' => $this->auth->id,
                    'user_check_name' => $user_checkInfo['name'],
                    'courses_category_name' => $courses_category_name,
                    'examination_message_name' => $examination_message_name,
                    'mechanism_category_zhuanye' => $mechanism_category_zhuanye,
                    'mechanism_category_jibie' => $mechanism_category_jibie,
                    'usered_score'=>$usered_score
                ];

//dump($data);
//exit;
                $r = $this->usersignup::Create($data);

                $this->success('订单创建时间', $r);

            } else {
                $this->error('报名计划不存在');
            }

        }

    /**
     * 报名详情
     * @param $order_sn
     */
        public  function orderInfo($order_sn){
            if($orderInfo=$this->usersignup->get(['order_sn'=>$order_sn])){
                $this->success('OK',$orderInfo);
            }else{
                $this->error('订单不存在');
            }
        }

    /**
     * 报名支付
     */
   public function payOrder($order_sn,$paytype,$method){

            if($orderInfo=$this->usersignup->get(['order_sn'=>$order_sn])){

                if($orderInfo['paystate']==1){
                    $this->error('订单已支付，无需重复支付');
                }

                $params = [
                    'amount'=>$orderInfo['price'],
                    'orderid'=>$orderInfo['order_sn'],
                    'type'=>$paytype,
                    'title'=>$orderInfo['examination_message_name'],
                    'notifyurl'=>request()->root(true).'/api/Notify/exam_notify/paytype/'.$paytype, //回调地址
                    'returnurl'=>'/',
                    'method'=>"scan",
                    'openid'=>"wx5049d19335c00bd7",
                ];

                $wxret = \addons\epay\library\Service::submitOrder($params);

              //  $wxret = \addons\epay\library\Service::submitOrder($params);
                if($paytype=='alipay'){
                    $r= $this->inviteshopQrcode($wxret['qr_code'],$paytype,$orderInfo['order_sn']);
                }elseif($paytype=='wechat'){
                    $r= $this->inviteshopQrcode($wxret['code_url'],$paytype,$orderInfo['order_sn']);
                }
                $this->success('OK',$r);
              //  $this->success('OK',$r);


            }else{
                $this->error('订单已支付');
            }



   }

    /**
     * 二维码生成
     * @param $qr_code
     * @param $paytype
     * @param $order_sn
     * @return string
     */


    public function inviteshopQrcode($qr_code,$paytype,$order_sn)
    {

        $image=$order_sn.'_'.$paytype.'.png';
        $result = Builder::create()
            ->writer(new PngWriter())
            ->writerOptions([])
            // ->data(Request::instance()->domain() . '/manystore?id=' . $uid)
            ->data($qr_code)
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
            ->size(300)
            ->margin(10)
            ->build();
        $result->saveToFile(ROOT_PATH . 'public/uploads/qrcode/'.$image);
        $exist = file_exists(ROOT_PATH . 'public/uploads/qrcode/'.$image);
        if (!$exist) $this->error('获取二维码失败');

        return   cdnurl('/uploads/qrcode/'.$image,true);

    }
    /**
     * 我的报名考试
     */
   public function mysignup(){
       $orderList=$this->usersignup->where('user_id',$this->auth->id)->order('createtime desc')->select();
        $this->success('OK',$orderList);
   }

    /**
     * 我的考试
     * @param int $page
     * @param int $limit
     * @param string $status
     */
    public function myexam($page=1,$limit=10,$status='全部'){
       $where['user_id']=['=',$this->auth->id];
        $where['paystate']=['=',1];
       if($status=='全部'){
           $where['step']=['in',['已支付','平台审核通过','工信部审核通过','平台拒绝','工信部拒绝','待考试','考试结束','派发证书','已报名','机构审核通过','机构审核拒绝','考试中']];
       }elseif($status=='未考试'){
           $where['step']=['in',['已支付','平台审核通过','工信部审核通过','平台拒绝','工信部拒绝','待考试']];
       }elseif($status=='已考试'){
           $where['step']=['in',['考试结束','派发证书','已报名','机构审核通过','机构审核拒绝','考试中']];
       }
        $orderList=$this->usersignup->where($where)->order('createtime desc')->paginate();
       foreach ($orderList as $key=>$value){


              $user_checkInfo=$this->user_check->where('id',$value['user_check_id'])->find();
           if($user_checkInfo){
               $user_check_avatar=$this->user->where('id',$user_checkInfo->user_id)->value('avatar');
               $orderList[$key]['user_checkInfo_aratar']=$user_check_avatar;
           }

       }
        $this->success('OK',$orderList);
    }

    /**
     * 获得补考计划
     */

    public  function  bukaoList($order_id){

        $orderInfo=$this->usersignup->where('user_id',$this->auth->id)->where('id',$order_id)->where('is_pass',0)->where('step','考试结束')->find();

        if(!$orderInfo){
            $this->error('未找到考试信息');
        }
         $where['admin_id']=$orderInfo['user_check_id'];
        $where['courses_category_id']=$orderInfo['courses_category_id'];
        $where['mechanism_category_topid']=$orderInfo['mechanism_category_topid'];
        $where['mechanism_category_id']=$orderInfo['mechanism_category_id'];
        $where['time']=$orderInfo['time'];
        $where['end_time']=$orderInfo['end_time'];

        $mechanismplanInfo = $this->mechanismplan->where($where)->select();

        $this->success('OK',$mechanismplanInfo);
    }

    /**
     *获得 申请补考
     */
    public  function makeUpExam($mobile=null,$captcha=null,$examination_mechanismplan_id){

        $where['id']=['=',$examination_mechanismplan_id];

      //  $where['admin_id']=['=',$user_check_id];

        $event = 'signup';
        if($mobile==null || $captcha==null){
            $this->error(__('手机号/短信验证码参数不全'));
        }

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }


        $ret = Smslib::setCheck($mobile, $captcha, $event);
        if (!$ret) {
            $this->error(__('短信验证码不正确'));
        }



        if ($mechanismplanInfo = $this->mechanismplan->get($where)) {



            if ($mechanismplanInfo->end_time < time()) {
                $this->error('报名计划已过期');
            }

            if($this->usersignup->where('user_id',$this->auth->id)->where('paystate',1)->where('examination_mechanismplan_id',$examination_mechanismplan_id)->find()){
                $this->error('您已报过名，无需重复报名');
            }



            //检测是否已报过名

            if (!$user_checkInfo = $this->user_check->get($mechanismplanInfo->admin_id)) {
                $this->error('机构已不存在');
            }

            //获得报名用户基本信息
            if (!$student = $this->student->where('user_id', $this->auth->id)->find()) {
                $this->error('未入驻学员什么不能报名');
            }
            if ($student->is_auth != '是') {
                $this->error('您还没有认证学员信息，请先认证');
            }

            if ($courses_categoryinfo = $this->courses_category->get($mechanismplanInfo['courses_category_id'])) {
                $courses_category_name = $courses_categoryinfo['name'];
            } else {
                $courses_category_name = '';
                $this->error('考试分类已删除或者不存在，请联系客服');
            }
            if ($examination_messageinfo = $this->message->get($mechanismplanInfo['examination_message_id'])) {
                $examination_message_name = $examination_messageinfo['name'];
            } else {
                $this->error('考试已被删除，请联系客服');
            }

            if ($mechanism_category_zhuanye = $this->mechanism_category->get($mechanismplanInfo->mechanism_category_topid)) {
                $mechanism_category_zhuanye = $mechanism_category_zhuanye['name'];
            } else {
                $this->error('专业已删除或者不存杂，请联系客服');
            }

            if ($mechanism_category_jibie = $this->mechanism_category->get($mechanismplanInfo->mechanism_category_id)) {
                $mechanism_category_jibie = $mechanism_category_jibie['name'];
            } else {
                $this->error('专业已删除或者不存杂，请联系客服');
            }
            $order_sn = "SN" . date('Ymd', time()) . rand(10000, 99999);
            $step = '已支付';
            $paystate = 1;
            $paytime = time();
//            if ($mechanismplanInfo['price'] > 0) {
//                $step = '待支付';
//                $paystate = 0;
//                $paytime = '';
//            }

            $data = [
                'order_sn' => $order_sn,
                'name' => $student['name'],
                'id_card' => $student['id_card'],
                'card_front_image' => $student['card_front_image'],
                'card_back_image' => $student['card_back_image'],
                'sex' => $student['sex'],
                'pinyin' => $student['pinyin'],
                'oldname' => $student['oldname'],
                'birthday' => $student['birthday'],
                'minzu' => $student['minzu'],
                'jiguan' => $student['jiguan'],
                'last_image' => $student['last_image'],
                'mianmao' => $student['mianmao'],
                'xueli' => $student['xueli'],
                'major' => $student['major'],
                'school' => $student['school'],
                'youbian' => $student['youbian'],
                'biye_school' => $student['biye_school'],
                'comeinschool' => $student['comeinschool'],
                'address' => $student['address'],
                'mobile' => $student['mobile'],
                'school_url' => $student['school_url'],
                'chuanzhen' => $student['chuanzhen'],
                'email' => $student['email'],
                'user_check_id' => $user_checkInfo['admin_id'],
                'courses_category_id' => $mechanismplanInfo['courses_category_id'],
                'mechanism_category_topid' => $mechanismplanInfo['mechanism_category_topid'],
                'mechanism_category_id' => $mechanismplanInfo['mechanism_category_id'],

                'examination_message_id' => $mechanismplanInfo['examination_message_id'],
                'examination_mechanismplan_id' => $examination_mechanismplan_id,
                'time' => $mechanismplanInfo['time'],
                'end_time' => $mechanismplanInfo['end_time'],
                'price' => $mechanismplanInfo['price'],
                'step' => $step,
                'paystate' => $paystate,
                'paytime' => $paytime,
                'user_id' => $this->auth->id,
                'user_check_name' => $user_checkInfo['name'],
                'courses_category_name' => $courses_category_name,
                'examination_message_name' => $examination_message_name,
                'mechanism_category_zhuanye' => $mechanism_category_zhuanye,
                'mechanism_category_jibie' => $mechanism_category_jibie,
                'is_bukao'=>'补考'
            ];


            $r = $this->usersignup::Create($data);

            $this->success('订单创建时间', $r);

        } else {
            $this->error('报名计划不存在');
        }

    }

    /***
     * 首页推荐考试
     */
    public function recommend(){
        $where['is_home']=['=','是'];
        $where['status']=['=','normal'];
        $messageList=$this->message->where($where)->select();

        foreach ($messageList as $key=>$value){
//dump();
//exit;
          $plan=$this->plan->where('examination_message_id',$value['id'])->select();


           foreach ($plan as $k=>$v){
//               dump($v['id']);
               if($v['end_time']<time()){
                   $plan[$k]['status']='已过期';
               }else{
                   $plan[$k]['status']='未过期';
               }
             // dump($v['user_check_ids']);
               //exit;

               if($v['user_check_ids']!=''){
                   $user_check_ids=explode(",",$v['user_check_ids']);

                   $plan[$k]['user_check']=$this->user_check->where('id','in',$user_check_ids)->select();
             }
               $plan[$k]['myd']=date("Y年m月d日",$v['time']);
               $plan[$k]['his']=date("H:i:s",$v['time']);
           }


            $messageList[$key]['plan']=$plan;

        }
        $this->success('OK',$messageList);

    }

    /**
     *专业/级别
     */
    public function major($user_check=null,$pid=0){
       if($user_check!=null){
          $user_checkInfo= $this->user_check->where('id',$user_check)->find();
           if($user_checkInfo){
               $mechanism_category_ids= $this->mechanism_category->where('id','in',explode(",",$user_checkInfo->mechanism_category_ids))->column('pid');
               array_unique($mechanism_category_ids);

           }
       }

        $this->success('OK',$this->mechanism_category->where('pid',$pid)->select());


    }

    /**
     * 专业列表
     * @param $user_check
     */
    public function jigoumajor($user_check=null){
        $where=[];
        if($user_check!=null){
            $user_checkInfo= $this->user_check->where('id',$user_check)->find();

            if($user_checkInfo){
               // dump();
              //  $mechanism_category_ids= $this->mechanism_category->where('id','in',explode(",",$user_checkInfo->mechanism_category_top_ids))->column('pid');

              $where['id']= ['in',explode(",",$user_checkInfo->mechanism_category_top_ids)] ;

            }
        }

       // $where['pid']=['=',0];
      //  dump($where);
        $this->success('OK',$this->mechanism_category->where($where)->select());

    }

    /**
     * 专业下所有级别
     */

    public  function  jigoujibie($user_check=null,$pid=null){

        $where=[];
        if($user_check!=null){
            $user_checkInfo= $this->user_check->where('id',$user_check)->find();
            $mechanism_category_ids=explode(",",$user_checkInfo->mechanism_category_ids);
            $where['id']= ['in',$mechanism_category_ids] ;
        }
        if($pid!=null){
            $where['pid']=['=',$pid];

        }else{
            $where['pid']=['>',0];
        }

       // dump($where);
        $this->success('OK',$this->mechanism_category->where($where)->select());
    }

    /**
     * 考试管理
     */

//$a= '<h3>php导出word函数？php怎么导出word格式数据?php怎么保存word格式数据到硬盘？php生成word数据浏览器下载</h3>';
    /**
     * 导出word方法 written:yangxingyi Data:2018-11-20 19:18
     * $wordnameAndPath,传入文件路径和文件名,(文件路径+文件名称),$content就是内容啦
     * $saveHdd默认不保存到硬盘.浏览器直接输出
     */
    public function putworld($wordnameAndPath='准考证',$saveHdd=false,$order_id)
    {

      if(!$usersignup=$this->usersignup->where('id',23)->find()){
          $this->error('未找到订单');
      }

        if($saveHdd===false){//浏览器直接输出
            ob_start(); //打开缓冲区
            header("Cache-Control: public");
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            if (strpos($_SERVER["HTTP_USER_AGENT"],'MSIE')) {
                header("Content-Disposition: attachment; filename={$wordnameAndPath}.doc");
            }else if (strpos($_SERVER["HTTP_USER_AGENT"],'Firefox')) {
                Header("Content-Disposition: attachment; filename={$wordnameAndPath}.doc");
            } else {
                header("Content-Disposition: attachment; filename={$wordnameAndPath}.doc");
            }
            header("Pragma:no-cache");
            header("Expires:0");
            echo '<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>准考证</title>
    <style>
        body {
            margin: 0;
            padding: 0;
        }

        .container {
            width: 210mm;
            /* A4纸宽度的一半（减去边距）*/
            /* height: 297mm; */
            /* A4纸的高度（减去边距）*/
            margin: 10mm auto;
            /* 上下左右边距 */
            padding: 18px 12px;
            padding-bottom: 0;
            box-sizing: border-box;
            border: 1px solid #000;
            /* 可选边框 */
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        tr,
        td {
            padding: 5mm 0;
            text-align: center;
        }

        th {
            width: 100px;
        }

        .cname>td:nth-child(2) {
            text-align: center;
        }

        .address>td {
            padding: 0;
            text-align: left;
            line-height: 5px;
            padding-left: 10px;
        }

        img {
            width: 150px;
            height: 100%;
        }
        .notice{
            line-height: 20px;
        }
        .notice>div:first-child{
            margin-top: 5px;
            margin-left: 5px;
        }
        .zhuyi{
            border: 2px solid #333;
            height: 40px;
            line-height: 40px;
            font-weight: 700;
            font-size: 20px;
        }
        .title{
            text-align: center;
        }
    </style>
</head>

<body>';

            $content=' <div class="title">
        <div>学信考试卷 202401 批次</div>
        <div>'.$usersignup["examination_message_name"].' 准考证</div>
    </div>
    <div class="container">
        <table border="1">
            <tbody>
                <tr class="cname">
                    <th>姓 名</th>
                    <td>崔福贵</td>
                    <th>性 别</th>
                    <td>男</td>
                    <td rowspan="4" class="avatar">
                        <img src="https://xuexinjiaoyu.xing-peng.com/uploads/20240528/e30b98fbcb81d89f54424ae49ca908f1.jpg" alt="">
                    </td>
                </tr>
                <tr>
                    <th>准考证号</th>
                    <td colspan="3">2401（批次）001（工信代码）41001（考点编号）000519</td>
                    <!-- <td></td> -->
                </tr>
                <tr>
                    <th>居民身份证</th>
                    <td colspan="3">'.$usersignup["id_card"].'</td>
                </tr>
                <tr>
                    <th>所在单位</th>
                    <td colspan="3">'.$usersignup["id_card"].'</td>
                </tr>
                <tr>
                    <th>职业名称</th>
                    <td colspan="2">企业人力资源管理师</td>
                    <td rowspan="2">报考等级</td>
                    <td colspan="2" rowspan="2">初级、中级、高级</td>
                </tr>
                <tr>
                    <th>工种名称</th>
                    <td colspan="2">----</td>
                </tr>
                <tr>
                    <th>考试科目</th>
                    <td colspan="2">理论 技能</td>
                    <td>文化程度</td>
                    <td colspan="2">大学本科</td>
                </tr>
                <tr class="address">
                    <th>理论考试地点</th>
                    <td colspan="4">
                        <p>网上考试：学信考试卷（202401批次电子试卷）</p>
                        <p>纸质考场：河南省数字商务中心1号考场（座位号：42） 郑州市二七区航海中路106号</p>
                    </td>
                </tr>
                <tr>
                    <th>理论考试地点</th>
                    <td colspan="4" style="text-align: left;padding-left: 10px;">
                        2024-01-27 12:10～13:40（机考）
                    </td>
                </tr>
                <tr class="address">
                    <th>技能考试地点</th>
                    <td colspan="4">
                        <p>网上考试：学信考试卷（202401批次电子试卷）</p>
                        <p>纸质考场：河南省数字商务中心1号考场（座位号：42） 郑州市二七区航海中路106号</p>
                    </td>
                </tr>
                <tr>
                    <th>技能考试时间</th>
                    <td colspan="4" style="text-align: left;padding-left: 10px;">
                        2024-01-27 12:10～13:40（机考）
                    </td>
                </tr>
                <tr class="address">
                    <th>综合考试地点</th>
                    <td colspan="4">
                        <p>网上考试：学信考试卷（202401批次电子试卷）</p>
                        <p>纸质考场：河南省数字商务中心1号考场（座位号：42） 郑州市二七区航海中路106号</p>
                    </td>
                </tr>
                <tr>
                    <th>综合考试时间</th>
                    <td colspan="4" style="text-align: left;padding-left: 10px;">
                        2024-01-27 12:10～13:40（机考）
                    </td>
                </tr>
            </tbody>
        </table>
        <div class="notice">
            <div>注意事项：</div>
            <div>1、考试前15分钟凭准考证和身份证入场，对号入座，并将证件放在桌子左上角，其他证件、 证明均无效；</div>
            <div>2、只准带墨水笔（圆珠笔）、2B铅笔、直尺、橡皮、铅笔刀入座。与考场无关的物品，按规 定存放在考场指定位置。移动电话等通信设备，应切断电源；</div>
            <div>3、开考30分钟内考生不得擅自离场，开考30分钟后迟到考生不得擅自进入考场；</div>
            <div>4、遵守考场规则，考试时不准旁窥、交谈、吸烟、传递物品、严禁作弊。交卷后不得在考场 附近逗留或者谈论；</div>
            <div>5、如遇试卷分发错误、印刷字迹模糊等问题可举手询问，不得要求监考人员解释试题； </div>
            <div>7、服从考试工作人员管理、监督和检查，不得无理取闹，违者取消考试资格；</div>
            <div>8、使用网上报名的考生，考试结束后可通过网上报名系统查询成绩，请关注报名系统通知消 息。</div>
        </div>
        <div class="zhuyi">注：如果您参加机考，考试账号为身份证号，考试校验码为身份证后6位。</div>
        <div>网上考试地址： http://www.chsie.com.cn</div>
    </div>';
            echo $content;
            echo "</body></html>";
            ob_end_flush();
        }else{//保存到硬盘,适合导出数据量大的，在cli模式下执行
            ob_start();
            echo '<html xmlns:o="urn:schemas-microsoft-com:office:office"
    xmlns:w="urn:schemas-microsoft-com:office:word"
    xmlns="http://www.w3.org/TR/REC-html40">';
            $wordnameAndPath .= '.doc';

            $wordnameAndPath  = iconv('UTF-8','GBK',$wordnameAndPath);//防止乱码
            $content=iconv('UTF-8','GBK',  $content); //防止乱码


            echo $content;
            echo "</html>";
            $data = ob_get_contents();
            ob_end_clean();

            $fp=fopen($wordnameAndPath,"wb");
            fwrite($fp,$data);
            fclose($fp);
            ob_flush();//每次执行前刷新缓存
            flush();
        }
    }

}
